# -*- coding: cp936 -*-
from db import DbThread
import Queue,threading,time



class SaveThread(threading.Thread):
    def __init__(self, queue):  
        threading.Thread.__init__(self)  
        self.queue = queue
        self.dbThreads = []
        for i in range(4):
            dbThread = DbThread()
            dbThread.setDaemon(True)
            dbThread.start()
            self.dbThreads.append( dbThread )
        self.dbThreadNum = len(self.dbThreads)
        
   
    def run(self): #Overwrite run() method, put what you want the thread do here  
        print "saveThread start"
        queue = self.queue
        threadID =  0
        while True:
            if queue.qsize()> 0:
                hash_id = queue.get()
                print "thread hash:" + hash_id
                
                self.dbThreads[threadID].put(hash_id)
                threadID = threadID+1
                if threadID >= self.dbThreadNum: threadID = 0
                
            else:
                time.sleep(1) 
                
    def stop(self):  
        self.thread_stop = True
        
            
if __name__ == "__main__":
    queue = Queue.Queue() 
    saveThread = SaveThread(queue)
    try:
        saveThread .setDaemon(True)
        saveThread.start()
    except:
        print "Error: unable to start thread"
        exit()

        
    for hashID in open("./sync/201201.txt")  :
        queue.put(hashID[:-1])
    while queue.qsize() > 0:
        print "left:" + str(queue.qsize())
        time.sleep(10)
        
    
